import React, { useCallback, useEffect, useState } from 'react'
import { View, Text } from '@tarojs/components'
import api from '@API'
import i18n from '@I18N'
import Taro from '@tarojs/taro'
import Navigate from '@NAVIGATION/navigateManager'
import { Analytic_Type } from '@CONSTANTS/analytic'
import { PlanManagementITF } from '@INTERFACES/PlanManagement'
import ManagementCard from '@COMPONENTS/PlanManagement/ManagementCard'
import ManagementCardPlaceholder from '@COMPONENTS/Placeholder/ManagementCardPlaceholder'
import style from './ExpertPlanList.module.scss'

interface Props {
  refreshing: boolean,
  isShowBanner: boolean,
}

const containerWithBannerStyle = { marginTop: '16px' }
const containerWithoutBannerStyle = { marginTop: '12px' }

const ExpertPlanList: React.FC<Props> = ({ refreshing, isShowBanner }) => {
  const language = 'zh'
  const [data, setData] = useState<PlanManagementITF[]>([])
  const [first, setFirst] = useState(true)
  const [loading, setLoading] = useState(true)

  const onClick = useCallback(item => {
    Navigate.managePlan({ tId: item.p8Id })
    Taro.tracker.trackEvent(Analytic_Type.tap_expert_plan_card.eventId, { Title: item?.Title?.[language] })
  }, [language])

  useEffect(() => {
    if (first || refreshing) {
      setLoading(true)
      api.getAndSortRecommendPainManagements({ dta: true }).then(result => {
        setFirst(false)
        setData(result.Templates)
      }).catch(error => {
        Taro.showToast({
          title: error?.message || error,
          icon: 'none',
        })
      }).finally(() => setLoading(false))
    }
  }, [first, refreshing, setLoading])

  return (
    <View className={style.container} style={isShowBanner ? containerWithBannerStyle : containerWithoutBannerStyle}>
      <View className={style.title}><Text>{i18n.patient.recommendedManagement()}</Text></View>
      {loading && <ManagementCardPlaceholder count={5} />}
      {data.map((item, idx) => (
        <ManagementCard
          key={`${item.p8Id || item.TemplateId}_${idx}`}
          language={language}
          data={item}
          onClick={onClick}
        />
      ))}
    </View>
  )
}

export default React.memo(ExpertPlanList)
